/**
 * @date 2006-7-7
 */

package org.nanhill.moo.service.impl;

import java.util.Date;
import java.util.List;

import org.nanhill.commons.id.DigestUtils;
import org.nanhill.commons.model.pagination.Pagination;
import org.nanhill.commons.model.pagination.ThreePartNumberPagination;
import org.nanhill.commons.pattern.domain.DomainAlreadyExistException;
import org.nanhill.commons.pattern.domain.DomainNotFoundException;
import org.nanhill.moo.dao.UserDao;
import org.nanhill.moo.domain.User;
import org.nanhill.moo.service.UserService;

/**
 * @author alin [xalinx at gmail dot com]
 * @date 2006-7-7
 */
public class UserServiceImpl extends AbstractService implements UserService {
	private UserDao userDao;

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.nanhill.moo.service.UserService#logon(java.lang.String,
	 *      java.lang.String)
	 */
	public User logon(String email, String password)
			throws DomainNotFoundException {
		User logon = this.userDao.findByEmailPassword(email, DigestUtils
				.md5Hex(password));
		if (null == logon) {
			throw new DomainNotFoundException();
		}
		return logon;
	}

	public User loadById(long uid) throws DomainNotFoundException {
		User load = this.userDao.findById(uid);
		if (null == load) {
			throw new DomainNotFoundException();
		}
		return load;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.nanhill.moo.service.UserService#forbid(long)
	 */
	public void forbid(long userId) {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.nanhill.moo.service.UserService#open(org.nanhill.moo.domain.User)
	 */
	public void open(User user) throws DomainAlreadyExistException {
		User old = this.userDao.findByEmail(user.getEmail());
		// user already exist
		if (old != null) {
			throw new DomainAlreadyExistException();
		}
		user.setPassword(DigestUtils.md5Hex(user.getPassword()));
		user.setCreateTime(new Date());
		this.userDao.save(user);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.nanhill.moo.service.UserService#page(int)
	 */
	public Pagination<User> loadPageLatest(int pageId, int pageSize) {
		int start = pageSize * (pageId - 1);
		List<User> users = userDao.findLatestPart(start, pageSize);
		long count = userDao.findCount();
		ThreePartNumberPagination<User> userPage = new ThreePartNumberPagination<User>();
		userPage.setPages(users.iterator());
		userPage.setCount(count);
		userPage.setPageId(pageId);
		userPage.setPageSize(pageSize);
		return userPage;
	}
}
